//
//  ByRecordWorkListForemanVC.m
//  recordworktool_ios
//
//  Created by mc on 2017/12/19.
//  Copyright © 2017年 ZhangZhanbin. All rights reserved.
//

#import "ByRecordWorkListForemanVC.h"
#import "ZZBPopView.h"
#import "ByMonthDatePicker.h"
#import "ByRecordListForemanCell.h"
#import "ByHomeTitleValueView.h"
#import "ByTitleViewControl.h"
#import "ByDetermineCancelView.h"
#import "ByAccountDetailVC.h"

@interface ByRecordWorkListForemanVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ZKBombView *monthDateView;
@property (nonatomic, strong) UILabel *titleLebel;
@property (nonatomic, assign) NSInteger year;
@property (nonatomic, assign) NSInteger month;
@property (nonatomic, assign) NSInteger day;

@property (nonatomic, strong) ZKBombView *dayDateView;

@property (nonatomic, strong) ZKBombView *peopleView;

@property (nonatomic, strong) NSMutableArray *dataArray;


@property (nonatomic, strong) ByNetModel *totalModel;

@property (nonatomic, strong) NSMutableArray *nameArray;
 @property (nonatomic, strong) UIPickerView *pickerView;
@property (nonatomic, copy) NSString *name;

@end

@implementation ByRecordWorkListForemanVC

- (NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray arrayWithCapacity:1];
    }
    return _dataArray;
}

- (NSMutableArray *)nameArray{
    if (_nameArray == nil) {
        _nameArray = [NSMutableArray arrayWithCapacity:1];
    }
    return _nameArray;
}

- (UIPickerView *)pickerView{
    if (_pickerView ==nil) {
        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, 200)];
        [_pickerView setDelegate:self];
        [_pickerView setDataSource:self];
    }
    return _pickerView;
}

- (ZKBombView *)peopleView{
    if (_peopleView == nil) {
        _peopleView = [[ZKBombView alloc] init];
        _peopleView.popMode = ZKBombPopModeBottom;
        _peopleView.positionMode = ZKBombPositionModeBottom;
        
        UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 240)];
        contentView.backgroundColor = [UIColor whiteColor];
        
        
        [contentView addSubview:self.pickerView];
        [self.pickerView reloadAllComponents];
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
        ByDetermineCancelView *titleView = [[ByDetermineCancelView alloc] init];
        [contentView addSubview:titleView];
        [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(contentView).offset(0);
            make.top.equalTo(contentView).offset(0);
            make.right.equalTo(contentView).offset(0);
            make.height.mas_equalTo(@40);
        }];
        
       
        if (self.nameArray.count > 0) {
            self.name = [self.nameArray firstObject];
        }else{
            self.name = nil;
        }
        titleView.determine = ^(){
            NSLog(@"确定");
            [_peopleView remove];
            _peopleView = nil;
            [self recordWorkData:[self getTimeStrWithYear:self.year month:self.month day:self.day]name:self.name];
        };
        titleView.cancel = ^(){
            NSLog(@"取消");
            [_peopleView remove];
            _peopleView = nil;
        };
        titleView.all = ^(){
            NSLog(@"确定");
            [_peopleView remove];
            _peopleView = nil;
            [self recordWorkData:[self getTimeStrWithYear:self.year month:self.month day:self.day]name:nil];
            self.name = nil;
        };
        
        _peopleView.contentView = contentView;
    }
    return _peopleView;
}


- (ZKBombView *)dayDateView{
    if (_dayDateView == nil) {
        _dayDateView = [[ZKBombView alloc] init];
        _dayDateView.popMode = ZKBombPopModeBottom;
        _dayDateView.positionMode = ZKBombPositionModeBottom;
        
        UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 240)];
        contentView.backgroundColor = [UIColor whiteColor];
        
        ByDetermineCancelView *titleView = [[ByDetermineCancelView alloc] init];
        [contentView addSubview:titleView];
        [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(contentView).offset(0);
            make.top.equalTo(contentView).offset(0);
            make.right.equalTo(contentView).offset(0);
            make.height.mas_equalTo(@40);
        }];
        
        self.day = 1;
        titleView.determine = ^(){
            NSLog(@"确定");
            [_dayDateView remove];
            _dayDateView = nil;
            [self recordWorkData:[self getTimeStrWithYear:self.year month:self.month day:self.day]name:nil];
            
        };
        titleView.cancel = ^(){
            NSLog(@"取消");
            [_dayDateView remove];
             _dayDateView = nil;
        };
        titleView.all = ^(){
            NSLog(@"确定");
            [_dayDateView remove];
            _dayDateView = nil;
            [self recordWorkData:[self getTimeStrWithYear:self.year month:self.month day:0]name:nil];
            self.day = 0;
        };
        
        
        NSMutableArray *dataArray = [self getDays:self.year month:self.month];
        ZKPickerView *pickerView = [[ZKPickerView alloc] initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, 200)];
        [contentView addSubview:pickerView];
        
        [pickerView setArratData:@[[dataArray copy]] andInitRows:@[@"1"]];
        pickerView.pickerDidSelected = ^(NSArray *items){
            NSLog(@"%@", [items firstObject]);
            self.day = [[items firstObject] integerValue];
        };
        
        
        
        _dayDateView.contentView = contentView;
        
    }
    return _dayDateView;
}

- (NSMutableArray *)getDays:(NSInteger)year month:(NSInteger)month {
    NSInteger day = 0;
    if((month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12))
    {
        day = 31 ;
    }
    if((month == 4) || (month == 6) || (month == 9) || (month == 11))
    {
        day = 30;
    }
    if (month == 2) {
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
        {
            // 闰年
            day = 29;
        }
        else
        {
            // 平年
            day = 28;
        }
    }
    
    NSMutableArray *temp = [[NSMutableArray alloc] init];
    for (NSInteger i = 1; i <= day; i ++) {
        [temp addObject:[NSString stringWithFormat:@"%li", i]];
    }
    
    return temp;
}




- (ZKBombView *)monthDateView{
    if (_monthDateView == nil) {
        _monthDateView = [[ZKBombView alloc] init];
        _monthDateView.popMode = ZKBombPopModeBottom;
        _monthDateView.positionMode = ZKBombPositionModeBottom;
        _monthDateView.usePickerTitleForCustomContentMode = YES;
        
        ByMonthDatePicker *pick = [[ByMonthDatePicker alloc] init];
        pick.frame = CGRectMake(0, 0, SCREEN_WIDTH, 240);
        _monthDateView.contentView = pick;
        __weak typeof(self) weakSelf = self;
        _monthDateView.removeBlock = ^(){
            NSLog(@"取消");
        };
        pick.dateDidPicker = ^(NSArray *dateArray){
            NSLog(@"year = %@, month = %@", [dateArray firstObject], [dateArray lastObject]);
            weakSelf.year = [[dateArray firstObject] integerValue];
            weakSelf.month  = [[dateArray lastObject] integerValue];
        };
        _monthDateView.customTapOk = ^(){
            NSLog(@"确定");
            weakSelf.titleLebel.text = [NSString stringWithFormat:@"%ld年%ld月", weakSelf.year,weakSelf.month];
            [weakSelf recordWorkData:[weakSelf getTimeStrWithYear:weakSelf.year month:weakSelf.month day:0]name:nil];
        };
        
       
        
        
    }
    return _monthDateView;
}

- (NSString *)getTimeStrWithYear:(NSInteger )year month:(NSInteger )month day:(NSInteger )day{
    
    NSString *monthStr = @"";
    NSString *dayStr = @"";
    
    if (month < 10) {
        monthStr = [NSString stringWithFormat:@"0%ld", month];
    }else{
        monthStr = [NSString stringWithFormat:@"%ld", month];
    }
    if (day == 0) {
        dayStr = @"";
    }else{
        
        if (day < 10) {
            dayStr = [NSString stringWithFormat:@"0%ld", day];
        }else{
            dayStr = [NSString stringWithFormat:@"%ld", day];
        }
    }
    return [NSString stringWithFormat:@"%ld%@%@", year,monthStr,dayStr];
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addLeftBackBarButtonItem];
    self.title = @"记工清单";
    
    [self initViews];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];
    
    self.year =  components.year;
    self.month = components.month;
    self.day = 0;
    
    [self loadData];
    [self recordWorkData:[self getTimeStrWithYear:self.year month:self.month day:0]name:nil];
    // Do any additional setup after loading the view.
}

- (void)loadData{
    
    ByNetModel *netModel = [[ByNetModel alloc] init];
    netModel.mobile = BY_USER.mobile;
    [ByApiRecord financeBillOverseer:netModel success:^(ByNetBaseResult *result) {
        
        NSDictionary *dic = result.data[@"total"];
        self.totalModel = [[ByNetModel alloc] initContentWithDic:dic];
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        
    } failure:^(ByNetBaseResult *result){
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
    
}

- (void)recordWorkData:(NSString *)daytime name:(NSString *)name{
    
    ByNetModel *netModel = [[ByNetModel alloc] init];
    netModel.uid = BY_USER.uid;
    netModel.daytime = daytime;
    netModel.mobile = BY_USER.mobile;
    netModel.name = name;
    [ByCoreToolAlert showLoadind:@"加载中"];
    [ByApiRecord queryOverseer:netModel success:^(ByNetBaseResult *result){
        
        [ByCoreToolAlert hideHud];
        self.dataArray = result.data;
        for (int i = 0; i < self.dataArray.count; i++) {
            ByNetModel *netModel = [self.dataArray objectAtIndex:i];
            if (![self.nameArray containsObject:netModel.worker_name]) {
                [self.nameArray addObject:netModel.worker_name];
            }
            
        }
        [self.tableView reloadData];
    } failure:^(ByNetBaseResult *result){
        
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
    
}





- (void)initViews{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - STATUS_NAV) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = BY_BACKGROUND_COLOR;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }else{
        if (self.dataArray.count > 0) {
            return 1;
        }else{
            return 0;
        }
       
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        static NSString *cellIdentifier = @"UITableViewCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        
        for (UIView *view in cell.contentView.subviews) {
            [view removeFromSuperview];
        }
        
        UILabel *titleLabel = [[UILabel alloc] init];
        [cell.contentView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell.contentView).offset(0);
            make.right.equalTo(cell.contentView).offset(0);
            make.top.equalTo(cell.contentView).offset(30);
            make.height.mas_equalTo(@20);
        }];
        titleLabel.font = FONT(16);
        titleLabel.textColor = TEXT_COLOR;
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.text = @"还需支付";
        
        UILabel *priceLabel = [[UILabel alloc] init];
        [cell.contentView addSubview:priceLabel];
        [priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell.contentView).offset(0);
            make.right.equalTo(cell.contentView).offset(0);
            make.top.equalTo(titleLabel.mas_bottom).offset(0);
            make.height.mas_equalTo(@50);
        }];
        priceLabel.font = FONT(35);
        priceLabel.textAlignment = NSTextAlignmentCenter;
        priceLabel.textColor = BY_THEME_COLOR;
        priceLabel.text = [NSString stringWithFormat:@"%.2f", self.totalModel.debt.floatValue];
        
        
        
        UIView *view = [[UIView alloc] init];
        [cell.contentView addSubview:view];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell.contentView).offset(120);
            make.left.equalTo(cell.contentView).offset(50);
            make.right.equalTo(cell.contentView).offset(-50);
            make.height.mas_equalTo(@80);
        }];
        
        CGFloat width = (SCREEN_WIDTH - 100) / 3.0;
        CGFloat height = 50;
        
        
        ByHomeTitleValueView *leftView = [[ByHomeTitleValueView alloc] init];
        [view addSubview:leftView];
        [leftView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view).offset(0);
            make.top.equalTo(view).offset(0);
            make.size.mas_equalTo(CGSizeMake(width, height));
        }];
        leftView.titleLabel.textColor = [UIColor blackColor];
        leftView.titleLabel.text = [NSString stringWithFormat:@"%.2f",self.totalModel.expenditure.floatValue];
        leftView.valueLabel.text = @"应收总和";
        leftView.titleLabel.font = FONT(14);
        leftView.valueLabel.font = FONT(14);
        
        [leftView.valueLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(@20);
        }];
        leftView.valueLabel.textColor = [UIColor blackColor];
        
        ByHomeTitleValueView *rightView = [[ByHomeTitleValueView alloc] init];
        [view addSubview:rightView];
        [rightView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(view).offset(0);
            make.top.equalTo(view).offset(0);
            make.size.mas_equalTo(CGSizeMake(width, height));
        }];
        rightView.titleLabel.text = [NSString stringWithFormat:@"%.2f", self.totalModel.settlement.floatValue];
        rightView.valueLabel.text = @"结算金额";
        rightView.titleLabel.font = FONT(14);
        rightView.valueLabel.font = FONT(14);
        rightView.titleLabel.textColor = [UIColor blackColor];
        rightView.valueLabel.textColor = [UIColor blackColor];
        [rightView.valueLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(@20);
        }];
        
        ByHomeTitleValueView *centerView = [[ByHomeTitleValueView alloc] init];
        [view addSubview:centerView];
        [centerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(view).offset(0);
            make.top.equalTo(view).offset(0);
            make.size.mas_equalTo(CGSizeMake(width, height));
        }];
        centerView.titleLabel.text = [NSString stringWithFormat:@"%.2f", self.totalModel.pre_borrow.floatValue];
        centerView.valueLabel.text = @"借支总额";
        centerView.titleLabel.textColor = [UIColor blackColor];
        centerView.valueLabel.textColor = [UIColor blackColor];
        centerView.titleLabel.font = FONT(14);
        centerView.valueLabel.font = FONT(14);
        [centerView.valueLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(@20);
        }];
        
        
        UILabel *line = [[UILabel alloc] init];
        [view addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view).offset(width);
            make.top.equalTo(view).offset(0);
            make.size.mas_equalTo(CGSizeMake(1, 60));
        }];
        line.backgroundColor = BY_LINE_COLOR;
        
        UILabel *line2 = [[UILabel alloc] init];
        [view addSubview:line2];
        [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(view).offset(-width);
            make.top.equalTo(view).offset(0);
            make.size.mas_equalTo(CGSizeMake(1,60));
        }];
        line2.backgroundColor = BY_LINE_COLOR;
        
        
        
        
        
        return cell;
        
    }else{
        
        ByRecordListForemanCell *cell = [ByRecordListForemanCell cellWithTableView:tableView];
        cell.dataArray = self.dataArray;
        cell.indexAtView = ^(NSInteger index){
            NSLog(@"index = %ld", index);
            ByNetModel *netModel = [self.dataArray objectAtIndex:index];
            ByAccountDetailVC *vc = [[ByAccountDetailVC alloc] init];
            vc.type = 0;
            vc.netModel = netModel;
            [self by_normalPush:vc hasNavi:YES];
            
        };
        return cell;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 120 * 2 - 20 - 20;
    }else{
        
        return 60 * self.dataArray.count;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.01;
    }else{
        return 80;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return [UIView new];
    }else{
        UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 80)];
        header.backgroundColor = BY_BACKGROUND_COLOR;
        UILabel *titleLebel = [[UILabel alloc] init];
        [header addSubview:titleLebel];
        [titleLebel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(header).offset(5);
            make.bottom.equalTo(header).offset(-5 - 50);
            make.right.equalTo(header).offset(-200);
            make.height.mas_equalTo(@20);
        }];
        titleLebel.text = [NSString stringWithFormat:@"%ld年%ld月", self.year,self.month];//@"2017年10月";
        titleLebel.textColor = TEXT_COLOR;
        titleLebel.font = FONT(16);
        self.titleLebel = titleLebel;
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [header addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(header).offset(-5);
            make.bottom.equalTo(titleLebel.mas_bottom).offset(0);
            make.size.mas_equalTo(CGSizeMake(80, 20));
        }];
        [button setTitle:@"其他月份" forState:UIControlStateNormal];
        [button setTitleColor:TEXT_COLOR forState:UIControlStateNormal];
        [button addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        button.titleLabel.font = FONT(16);
        
        ByTitleViewControl *timeControl = [[ByTitleViewControl alloc] init];
        [header addSubview:timeControl];
        [timeControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(header).offset(40);
            make.bottom.equalTo(header).offset(-15);
            make.size.mas_equalTo(CGSizeMake(40 + 22 + 5, 22));
        }];
        timeControl.tag = 100;
        ByTitleViewControl *nameControl = [[ByTitleViewControl alloc] init];
        [header addSubview:nameControl];
        [nameControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(header).offset(0);
            make.bottom.equalTo(timeControl.mas_bottom).offset(0);
            make.size.mas_equalTo(CGSizeMake(40 + 22 + 5, 22));
        }];
        nameControl.titleLabel.text = @"姓名";
        nameControl.tag = 200;
        [timeControl addTarget:self action:@selector(controlAciton:) forControlEvents:UIControlEventTouchUpInside];
        [nameControl addTarget:self action:@selector(controlAciton:) forControlEvents:UIControlEventTouchUpInside];
        return header;
    }
    
}

- (void)controlAciton:(UIControl *)control{
    if (control.tag == 100) {
        NSLog(@"日期");
        [self.dayDateView show];
    }else{
        NSLog(@"姓名");
        [self.peopleView show];
    }
    
}


- (void)btnAction:(UIButton *)btn{
    
    NSLog(@"其他月份");
    [self.monthDateView show];
}



#pragma mark - picker delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.nameArray.count;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 44;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    
    return SCREEN_WIDTH;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    self.name = [self.nameArray objectAtIndex:row];
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view {
    
    UILabel *label = [[UILabel alloc] init];
    [label setTextAlignment:NSTextAlignmentCenter];
    label.text = self.nameArray[row];
    return label;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
